<template>
  <el-dialog
    v-el-drag-dialog
    title="创建安检计划"
    :visible.sync="visible"
    width="700px"
    @closed="reset"
  >
    <el-form ref="dataForm" class="form" :rules="rules" :model="temp" label-position="left" label-width="120px">

      <el-form-item label="计划名称:" prop="planName" style="width: 100%;">
        <el-input v-model="temp.planName" placeholder="请输入计划名称" clearable />
      </el-form-item>

      <el-form-item label="安检范围:" prop="orgIds">
        <el-tree-select
          v-model="temp.orgIds"
          :clearable="false"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            multiple: true,
            placeholder: '请选择',
          }"
          :tree-params=" {
            'default-expand-all': true,
            'expand-on-click-node': false,
            'highlight-current': true,
            props:{
              value:'orgId',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
        />
      </el-form-item>

      <el-form-item label="客户类型:" prop="mineStatus" label-width="120px">
        <el-select v-model="temp.mineStatus" placeholder="请选择客户类型" multiple :popper-append-to-body="false" @change="selectChange">
          <el-option :value="mineStatusValue" style="height: auto;">
            <el-tree ref="tree" :data="csmData" show-checkbox node-key="id" highlight-current :props="defaultProps" default-expand-all @check-change="handleCheckChange" />
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item class="merge-item" label="安检到期时间在:" style="width: 100%;">
        <el-date-picker
          v-model="date"
          type="daterange"
          range-separator="到"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">
        关闭
      </el-button>
      <el-button type="primary" @click="success">
        生成
      </el-button>
    </div>
    <newly-increased ref="newlyIncreased" :csm-type-map="csmTypeMap" :tree-data="treeData" :csm-status-map="csmStatusMap" />
  </el-dialog>
</template>

<script>
  import { gasCheckPlanClientAssignSave } from '@/api'
  import NewlyIncreased from './NewlyIncreased'
  import moment from 'dayjs'

  export default {
    name: 'add',
    components: {
      NewlyIncreased
    },
    props: {
      csmTypeMap: {
        type: Array,
        required: true
      },
      treeData: {
        type: Array,
        required: true
      },
      csmStatusMap: {
        type: Array,
        required: true
      }
    },
    data() {
      return {
        visible: false,
        csmVal: 'csmRgPhone',
        date: [],
        temp: {
          planName: '',
          mineStatus: '',
          orgIds: []
        },
        params: {},
        rules: {
          planName: [{ required: true, message: '请输入计划名称', trigger: 'change' }],
          orgIds: [{ required: true, message: '请选择安检范围', trigger: 'change' }],
          mineStatus: [{ required: true, message: '请选择客户类型', trigger: 'change' }]
        },
        csmData: [{
          id: 0,
          label: '全部',
          children: [
            {
              id: 1,
              label: '居民'
            },
            {
              id: 2,
              label: '商业'
            },
            {
              id: 4,
              label: '工业'
            }
          ]
        }],
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        mineStatusValue: []
      }
    },
    computed: {
    },
    async created() {},
    methods: {
      open(temp) {
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
          this.$nextTick(() => {
            this.$refs.dataForm.clearValidate()
          })
        })
      },
      success() {
        const csmType = []
        this.mineStatusValue.map(item => {
          csmType.push(String(item.id))
        })
        const orgSNNos = []
        const scopeNames = []
        this.treeData.map(item => {
          orgSNNos.push(item.orgSNNo)
          scopeNames.push(item.orgName)
        })
        this.$refs.dataForm.validate(valid => {
          if (!valid) return
          this.params.csmType = csmType
          this.params.orgSNNos = orgSNNos
          this.params.scopeNames = String(scopeNames.join(','))
          this.params.orgIds = this.temp.orgIds
          this.params.planName = this.temp.planName
          this.params.beginDt = moment(this.date[0]).format()
          this.params.endDt = moment(this.date[1]).format()
          this.add()
        })
      },
      async add() {
        const res = await gasCheckPlanClientAssignSave(this.params)
        console.log('...res', res)
        var str = ''
        for (const k of this.temp.mineStatus.values()) {
          if (k !== '全部') {
            str += k + '用户 '
          }
        }
        const obj = {
          planCode: res.data,
          planName: this.temp.planName,
          csmTypes: str,
          scopeNames: this.params.scopeNames
        }
        this.visible = false
        this.$refs.newlyIncreased.open(obj)
      },
      // select框值改变时候触发的事件
      selectChange(e) {
        var arrNew = []
        var dataLength = this.mineStatusValue.length
        var eleng = e.length
        for (let i = 0; i < dataLength; i++) {
          for (let j = 0; j < eleng; j++) {
            if (e[j] === this.mineStatusValue[i].label) {
              arrNew.push(this.mineStatusValue[i])
            }
          }
        }
        this.$refs.tree.setCheckedNodes(arrNew)// 设置勾选的值
      },
      handleCheckChange() {
        const res = this.$refs.tree.getCheckedNodes(false, true) // 这里两个true，1. 是否只是叶子节点 2. 是否包含半选节点（就是使得选择的时候不包含父节点）
        const arrLabel = []
        const arr = []
        res.forEach(item => {
          arrLabel.push(item.label)
          arr.push(item)
        })
        this.mineStatusValue = arr
        this.temp.mineStatus = arrLabel
        // console.log('arr:' + JSON.stringify(arr))
        // console.log('arrLabel:' + arrLabel)
      },
      reset() {
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  flex-wrap: wrap;
  & /deep/ .el-form-item {
    width: 50%;
    padding-right: 10px;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
  /deep/.el-select-dropdown__item {
    padding: 0 !important;
    padding-right: 0 !important;
  }
}
</style>
